package com.ruicar.afs.cloud.apply.business.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.apply.business.mapper.ApplySmsSendMapper;
import com.ruicar.afs.cloud.apply.business.service.ApplyAdminService;
import com.ruicar.afs.cloud.apply.business.service.ApplySignRelationService;
import com.ruicar.afs.cloud.apply.business.service.ApplySmsSendService;
import com.ruicar.afs.cloud.apply.common.condition.SendMessageCondition;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.contract.service.ApplyCarInvoiceService;
import com.ruicar.afs.cloud.apply.pre.approve.service.PreApproveService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyCustBaseInfoService;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.service.AfsUser;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.MessageParamEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ResultBooleanEnum;
import com.ruicar.afs.cloud.message.sendmessage.dto.MessageDataDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendMessageDto;
import com.ruicar.afs.cloud.message.sendmessage.dto.SendResultInfoDto;
import com.ruicar.afs.cloud.message.sendmessage.service.MessageService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.ruicar.afs.cloud.apply.common.utils.ApplyConstants.*;

/**
 * @author: mingzhi.li
 * @date: 2020/8/7 16:45
 * @description:短信发送
 */
@Service
@AllArgsConstructor
public class ApplySmsSendServiceImpl extends ServiceImpl<ApplySmsSendMapper, ApplySmsSend> implements ApplySmsSendService {

    private final PreApproveService preApproveService;
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ApplySignRelationService applySignRelationService;
    private final ApplyAdminService applyAdminService;
    private final ApplyCarInvoiceService applyCarInvoiceService;
    private final MessageService messageService;
    @Override
    public IResponse send(SendMessageCondition condition) {
        /*暂时不随机生成验证码，默认1234*/
        //String verCode= random();
        String verCode= "1234";
        String smsContent = "尊敬的客户，您的签约验证码为："+verCode+",有效期为5分钟，请尽快完成签约。";
        AfsUser user = SecurityUtils.getUser();
        Date now = new Date();
        if(MESSAGE_TYPE_ONE.equals(condition.getMessageType())){
            //协议签约短信
            if(USAGESCENARIOS_TYPE_ZERO.equals(condition.getUsageScenarios())){
                //预审批
                PreApproveInfo info = null;
                if(condition.getPreId() !=null){
                    info = preApproveService.getOne(Wrappers.<PreApproveInfo>query().lambda()
                            .eq(PreApproveInfo::getId, condition.getPreId()));
                }else{
                    info = preApproveService.getOne(Wrappers.<PreApproveInfo>query().lambda()
                            .eq(PreApproveInfo::getCertNo, condition.getCertNo())
                            .eq(PreApproveInfo::getBusinessType,condition.getBusinessType())
                            .eq(PreApproveInfo::getCreateBy,user.getUsername()));
                }
                if(info!=null){
                    ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                            .eq(ApplySmsSend::getBusinessId, info.getId().toString()));
                    if(smsSend !=null){
                        //验证码
                        smsSend.setVerCode(verCode);
                        //短信内容
                        smsSend.setSendContent(smsContent);
                        //失效时间
                        smsSend.setDeadTime(new Date(now.getTime() + 300000));
                        this.updateById(smsSend);
                        //发送短信验证码
                        sendApplyMessageInfo(info.getTelPhone(),smsContent);
                    }else{
                        ApplySmsSend sms = new ApplySmsSend();
                        //业务id
                        sms.setBusinessId(info.getId());
                        //业务场景
                        sms.setBusinessType(USAGESCENARIOS_TYPE_ZERO);
                        //客户姓名
                        sms.setCustName(info.getCustName());
                        //手机号码
                        sms.setTelphone(info.getTelPhone());
                        //验证码
                        sms.setVerCode(verCode);
                        //短信内容
                        sms.setSendContent(smsContent);
                        //失效时间
                        sms.setDeadTime(new Date(now.getTime() + 300000));
                        this.save(sms);
                        //发送短信验证码
                        sendApplyMessageInfo(info.getTelPhone(),smsContent);
                    }
                }else{
                    return IResponse.fail("暂无数据");
                }
            }else if(USAGESCENARIOS_TYPE_ONE.equals(condition.getUsageScenarios())){
                ApplyCustBaseInfo custBaseInfo = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                        .eq(ApplyCustBaseInfo::getId,condition.getCustId().toString()));
                if(custBaseInfo!=null){
                    ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                            .eq(ApplySmsSend::getBusinessId, custBaseInfo.getId().toString()).eq(ApplySmsSend::getBusinessType,USAGESCENARIOS_TYPE_ONE));
                    if(smsSend !=null){
                        //验证码
                        smsSend.setVerCode(verCode);
                        //短信内容
                        smsSend.setSendContent(smsContent);
                        //失效时间
                        smsSend.setDeadTime(new Date(now.getTime() + 300000));
                        this.updateById(smsSend);
                        //发送短信验证码
                        sendApplyMessageInfo(custBaseInfo.getTelPhone(),smsContent);
                    }else{
                        ApplySmsSend sms = new ApplySmsSend();
                        //业务id
                        sms.setBusinessId(custBaseInfo.getId());
                        //业务场景
                        sms.setBusinessType(USAGESCENARIOS_TYPE_ONE);
                        //客户姓名
                        sms.setCustName(custBaseInfo.getCustName());
                        //手机号码
                        sms.setTelphone(custBaseInfo.getTelPhone());
                        //验证码
                        sms.setVerCode(verCode);
                        //短信内容
                        sms.setSendContent(smsContent);
                        //失效时间
                        sms.setDeadTime(new Date(now.getTime() + 300000));
                        this.save(sms);
                        //发送短信验证码
                        sendApplyMessageInfo(custBaseInfo.getTelPhone(),smsContent);
                    }
                }else{
                    return IResponse.fail("客户信息不存在");
                }
            }
        } else if(MESSAGE_TYPE_TWO.equals(condition.getMessageType())){
            //合同签约
            List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                    .eq(ApplySignRelation::getCustId, condition.getCustId().toString()));
            if(signRelationList !=null && signRelationList.size()>0){
                ApplySignRelation relation =signRelationList.get(0);
                if(WITNESSES.equals(relation.getCustRole())){
                    //签约角色见证人
                    IResponse vo = applyAdminService.getUserInfoByUsername(user.getUsername());
                    if(CODE_SUCCESS.equals(vo.getCode())){
                        Map map = (Map) vo.getData();
                        ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                                .eq(ApplySmsSend::getBusinessId, user.getId().toString()).eq(ApplySmsSend::getBusinessType,USAGESCENARIOS_TYPE_TWO));
                        if(smsSend !=null){
                            //验证码
                            smsSend.setVerCode(verCode);
                            //短信内容
                            smsSend.setSendContent(smsContent);
                            //失效时间
                            smsSend.setDeadTime(new Date(now.getTime() + 300000));
                            this.updateById(smsSend);
                            //发送短信验证码
                            sendApplyMessageInfo((String) map.get("phone"),smsContent);
                        }else{
                            ApplySmsSend sms = new ApplySmsSend();
                            //业务id
                            sms.setBusinessId(user.getId());
                            //业务场景
                            sms.setBusinessType(USAGESCENARIOS_TYPE_TWO);
                            //客户姓名
                            sms.setCustName(user.getUserRealName());
                            //手机号码
                            sms.setTelphone((String) map.get("phone"));
                            //验证码
                            sms.setVerCode(verCode);
                            //短信内容
                            sms.setSendContent(smsContent);
                            //失效时间
                            sms.setDeadTime(new Date(now.getTime() + 300000));
                            this.save(sms);
                            //发送短信验证码
                            sendApplyMessageInfo((String) map.get("phone"),smsContent);
                        }
                    }
                }else if(CAR_DEALER.equals(relation.getCustRole())){
                    ApplyCarInvoice applyCarInvoice = applyCarInvoiceService.getOne(Wrappers.<ApplyCarInvoice>query().lambda()
                            .eq(ApplyCarInvoice::getApplyNo, condition.getApplyNo())
                            .eq(ApplyCarInvoice::getInvoiceNature,"personal"));
                    if(applyCarInvoice !=null){
                        ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                                .eq(ApplySmsSend::getBusinessId, applyCarInvoice.getId().toString()).eq(ApplySmsSend::getBusinessType,USAGESCENARIOS_TYPE_TWO));
                        if(smsSend !=null){
                            //验证码
                            smsSend.setVerCode(verCode);
                            //短信内容
                            smsSend.setSendContent(smsContent);
                            //失效时间
                            smsSend.setDeadTime(new Date(now.getTime() + 300000));
                            this.updateById(smsSend);
                            //发送短信验证码
                            sendApplyMessageInfo(applyCarInvoice.getSalePhone(),smsContent);
                        }else{
                            ApplySmsSend sms = new ApplySmsSend();
                            //业务id
                            sms.setBusinessId(applyCarInvoice.getId());
                            //业务场景
                            sms.setBusinessType(USAGESCENARIOS_TYPE_TWO);
                            //客户姓名
                            sms.setCustName(applyCarInvoice.getSaleName());
                            //手机号码
                            sms.setTelphone(applyCarInvoice.getSalePhone());
                            //验证码
                            sms.setVerCode(verCode);
                            //短信内容
                            sms.setSendContent(smsContent);
                            //失效时间
                            sms.setDeadTime(new Date(now.getTime() + 300000));
                            this.save(sms);
                            //发送短信验证码
                            sendApplyMessageInfo(applyCarInvoice.getSalePhone(),smsContent);
                        }
                    }else{
                        return IResponse.fail("车商发票信息不存在");
                    }
                }else{
                    ApplyCustBaseInfo custBaseInfo = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                            .eq(ApplyCustBaseInfo::getId,condition.getCustId().toString()));
                    if(custBaseInfo!=null){
                        ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                                .eq(ApplySmsSend::getBusinessId, custBaseInfo.getId().toString()).eq(ApplySmsSend::getBusinessType,USAGESCENARIOS_TYPE_TWO));
                        if(smsSend !=null){
                            //验证码
                            smsSend.setVerCode(verCode);
                            //短信内容
                            smsSend.setSendContent(smsContent);
                            //失效时间
                            smsSend.setDeadTime(new Date(now.getTime() + 300000));
                            this.updateById(smsSend);
                            //发送短信验证码
                            sendApplyMessageInfo(custBaseInfo.getTelPhone(),smsContent);
                        }else{
                            ApplySmsSend sms = new ApplySmsSend();
                            //业务id
                            sms.setBusinessId(custBaseInfo.getId());
                            //业务场景
                            sms.setBusinessType(USAGESCENARIOS_TYPE_TWO);
                            //客户姓名
                            sms.setCustName(custBaseInfo.getCustName());
                            //手机号码
                            sms.setTelphone(custBaseInfo.getTelPhone());
                            //验证码
                            sms.setVerCode(verCode);
                            //短信内容
                            sms.setSendContent(smsContent);
                            //失效时间
                            sms.setDeadTime(new Date(now.getTime() + 300000));
                            this.save(sms);
                            //发送短信验证码
                            sendApplyMessageInfo(custBaseInfo.getTelPhone(),smsContent);
                        }
                    }else{
                        return IResponse.fail("客户信息不存在");
                    }
                }
            }
        }else if(MESSAGE_TYPE_THREE.equals(condition.getMessageType())){
            ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                    .eq(ApplySmsSend::getBusinessId, condition.getCaseId().toString()).eq(ApplySmsSend::getBusinessType,USAGESCENARIOS_TYPE_THREE));
            if(smsSend !=null){
                //验证码
                smsSend.setVerCode(verCode);
                //短信内容
                smsSend.setSendContent(smsContent);
                //失效时间
                smsSend.setDeadTime(new Date(now.getTime() + 300000));
                this.updateById(smsSend);
                //发送短信验证码
                sendApplyMessageInfo(condition.getTelPhone(),smsContent);
            }else{
                ApplySmsSend sms = new ApplySmsSend();
                //业务id
                sms.setBusinessId(condition.getCaseId());
                //业务场景
                sms.setBusinessType(USAGESCENARIOS_TYPE_THREE);
                //客户姓名
                sms.setCustName(condition.getCaseName());
                //手机号码
                sms.setTelphone(condition.getTelPhone());
                //验证码
                sms.setVerCode(verCode);
                //短信内容
                sms.setSendContent(smsContent);
                //失效时间
                sms.setDeadTime(new Date(now.getTime() + 300000));
                this.save(sms);
                //发送短信验证码
                sendApplyMessageInfo(condition.getTelPhone(),smsContent);
            }
        }
        return IResponse.success(verCode);
    }

    @Override
    public IResponse check(SendMessageCondition condition) {
        AfsUser user = SecurityUtils.getUser();
        Date nowDate = new Date();
        if(MESSAGE_TYPE_ONE.equals(condition.getMessageType())){
            //协议签约短信
            if(USAGESCENARIOS_TYPE_ZERO.equals(condition.getUsageScenarios())){
                //预审批
                PreApproveInfo info = null;
                if(condition.getPreId() !=null){
                    info = preApproveService.getOne(Wrappers.<PreApproveInfo>query().lambda()
                            .eq(PreApproveInfo::getId, condition.getPreId()));
                }else{
                    info = preApproveService.getOne(Wrappers.<PreApproveInfo>query().lambda()
                            .eq(PreApproveInfo::getCertNo, condition.getCertNo())
                            .eq(PreApproveInfo::getBusinessType,condition.getBusinessType())
                            .eq(PreApproveInfo::getCreateBy,user.getUsername()));
                }
                if(info!=null){
                    ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                            .eq(ApplySmsSend::getBusinessId, info.getId().toString()).eq(ApplySmsSend::getVerCode,condition.getRandomCode()));
                    if(smsSend ==null){
                        return IResponse.fail("验证码错误");
                    }
                    if(nowDate.after(smsSend.getDeadTime())){
                        return IResponse.fail("验证码已失效！");
                    }
                }else{
                    return IResponse.fail("请求参数异常");
                }
            }else if(USAGESCENARIOS_TYPE_ONE.equals(condition.getUsageScenarios())){
                ApplyCustBaseInfo custBaseInfo = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                        .eq(ApplyCustBaseInfo::getId,condition.getCustId().toString()));
                if(custBaseInfo!=null){
                    ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                            .eq(ApplySmsSend::getBusinessId, custBaseInfo.getId().toString())
                            .eq(ApplySmsSend::getVerCode,condition.getRandomCode()));
                    if(smsSend ==null){
                        return IResponse.fail("验证码错误");
                    }
                    if(nowDate.after(smsSend.getDeadTime())){
                        return IResponse.fail("验证码已失效！");
                    }
                }else{
                    return IResponse.fail("客户信息不存在");
                }
            }
        }else if(MESSAGE_TYPE_TWO.equals(condition.getMessageType())){
            //合同签约
            List<ApplySignRelation> signRelationList = applySignRelationService.list(Wrappers.<ApplySignRelation>query().lambda()
                    .eq(ApplySignRelation::getCustId, condition.getCustId().toString()));
            if(signRelationList !=null && signRelationList.size()>0){
                ApplySignRelation relation =signRelationList.get(0);
                if(WITNESSES.equals(relation.getCustRole())){
                    //签约角色见证人
                    IResponse vo = applyAdminService.getUserInfoByUsername(user.getUsername());
                    if(CODE_SUCCESS.equals(vo.getCode())){
                        ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                                .eq(ApplySmsSend::getBusinessId, user.getId().toString())
                                .eq(ApplySmsSend::getBusinessType,USAGESCENARIOS_TYPE_TWO)
                                .eq(ApplySmsSend::getVerCode,condition.getRandomCode()));
                        if(smsSend ==null){
                            return IResponse.fail("验证码错误");
                        }
                        if(nowDate.after(smsSend.getDeadTime())){
                            return IResponse.fail("验证码已失效！");
                        }
                    }
                }else if(CAR_DEALER.equals(relation.getCustRole())){
                    ApplyCarInvoice applyCarInvoice = applyCarInvoiceService.getOne(Wrappers.<ApplyCarInvoice>query().lambda()
                            .eq(ApplyCarInvoice::getApplyNo, condition.getApplyNo())
                            .eq(ApplyCarInvoice::getInvoiceNature,"personal"));
                    if(applyCarInvoice !=null){
                        ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                                .eq(ApplySmsSend::getBusinessId, applyCarInvoice.getId().toString())
                                .eq(ApplySmsSend::getBusinessType,USAGESCENARIOS_TYPE_TWO)
                                .eq(ApplySmsSend::getVerCode,condition.getRandomCode()));
                        if(smsSend ==null){
                            return IResponse.fail("验证码错误");
                        }
                        if(nowDate.after(smsSend.getDeadTime())){
                            return IResponse.fail("验证码已失效！");
                        }
                    }else{
                        return IResponse.fail("车商发票信息不存在");
                    }
                }else{
                    ApplyCustBaseInfo custBaseInfo = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda()
                            .eq(ApplyCustBaseInfo::getId,condition.getCustId().toString()));
                    if(custBaseInfo!=null){
                        ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                                .eq(ApplySmsSend::getBusinessId, custBaseInfo.getId().toString())
                                .eq(ApplySmsSend::getBusinessType,USAGESCENARIOS_TYPE_TWO)
                                .eq(ApplySmsSend::getVerCode,condition.getRandomCode()));
                        if(smsSend ==null){
                            return IResponse.fail("验证码错误");
                        }
                        if(nowDate.after(smsSend.getDeadTime())){
                            return IResponse.fail("验证码已失效！");
                        }
                    }else{
                        return IResponse.fail("客户信息不存在");
                    }
                }
            }
        }else if(MESSAGE_TYPE_THREE.equals(condition.getMessageType())){
            ApplySmsSend smsSend =this.getOne(Wrappers.<ApplySmsSend>query().lambda()
                    .eq(ApplySmsSend::getBusinessId, condition.getCaseId())
                    .eq(ApplySmsSend::getBusinessType,USAGESCENARIOS_TYPE_THREE)
                    .eq(ApplySmsSend::getVerCode,condition.getRandomCode()));
            if(smsSend ==null){
                return IResponse.fail("验证码错误");
            }
            if(nowDate.after(smsSend.getDeadTime())){
                return IResponse.fail("验证码已失效！");
            }
        }
        return IResponse.success(true);
    }

     String random() {
        //定义两变量
        int x;
         //实例化一个random的对象ne
        Random random=new Random();
         //为变量赋随机值1000-9999
        x=random.nextInt(9999-1000+1)+1000;
        return String.valueOf(x);
    }

    public void sendApplyMessageInfo(String phone,String smsContent) {
        SendMessageDto messageDto = new SendMessageDto();
        //短信类型：验证码
        messageDto.setChannel("0");
        messageDto.setCode(MessageParamEnum.CODE.getCode());
        messageDto.setTimestamp(System.currentTimeMillis() / 1000 + "");
        messageDto.setUid(MessageParamEnum.UID.getCode());
        List<MessageDataDto> dataDtoList = new ArrayList<>();
        MessageDataDto dataDto = new MessageDataDto();
        dataDto.setDeptId(MessageParamEnum.DEPTID.getCode());
        dataDto.setOrigin(MessageParamEnum.ORIGIN.getCode());
        dataDto.setPhone(phone);
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd");
        dataDto.setSummaryId(phone + sd.format(new Date()));
        dataDto.setSmsContent(smsContent);
        dataDto.setTemplateId("E01");
        //优先级：用户验证码发送
        dataDto.setPriority("5");
        dataDtoList.add(dataDto);

        messageDto.setMessageDataDto(dataDtoList);
        SendResultInfoDto sendResultInfoDto = messageService.sendMessageData(messageDto);
        if (ObjectUtils.isNotEmpty(sendResultInfoDto)) {
            if (sendResultInfoDto.getResult().equals(ResultBooleanEnum.TRUE.getCode())) {
            } else {
                throw new AfsBaseException("进件数据异常！");
            }
        } else {
            throw new AfsBaseException("短信接口响应失败！");
        }
    }

}
